<template>
	<transition :name="'slide-left'">
		<div class="select-box" :class="{ multiple: multiple }" v-show="showPanel" style="height:100%;width:100%;">
			<form class="select-search bottom-line" action="javascript:;">
				<van-icon name="arrow-left" @click="popStateEvent" />
				<!-- <form action="javascript:;"> -->
				<van-search
					class="search"
					show-action
					v-model.trim="keyword"
					:placeholder="placeholder"
					v-on:[`input`]="!keyword.trim() ? onSearch(keyword) : ''"
					@clear="onSearch(keyword)"
					@search="onSearch(keyword)"
					><template #action>
						<div @click="onSearch(keyword)">搜索</div>
					</template></van-search
				>
				<!-- </form> -->
			</form>
			<div class="head-nav" @touchmove.stop="movereturn">
				<ul class="nav-scroll" ref="scrollNav">
					<template v-if="!filterEmpData.length">
						<li
							class="nav-item"
							@click="active(index)"
							:class="[index > 0 && index == stepList.length - 1 ? 'active' : '']"
							v-for="(item, index) in stepList"
							:key="item.id"
						>
							{{ item.name }}<van-icon name="arrow" />
						</li>
					</template>
					<template v-else>
						<li class="nav-item" @click="active(0)">
							通讯录<van-icon name="arrow" />搜索结果（{{ filterEmpData.length }}）
						</li>
						<!-- <li class="nav-item active" @click="active(1)">太蓝新能源<van-icon name="arrow" /></li> -->
					</template>
				</ul>
			</div>
			<div class="container">
				<!-- 选部门 -->
				<template v-if="type == 1">
					<template v-if="!multiple">
						<label
							class="cell-item-dep bottom-line"
							@click="selectDep(item, index)"
							v-for="(item, index) in currentData"
							:key="index"
						>
							<span class="fullName">{{ item.F_FullName }}</span>
							<!-- <van-icon v-if="item.children.length" name="arrow" class="icon-arrow" /> -->
							<span class="child-icon" v-if="item.children.length" @click.self.stop="addDep(item, index)">下级</span>
						</label>
					</template>
					<van-checkbox-group v-if="multiple" v-model="selectData">
						<label class="cell-item-dep bottom-line" v-for="(item, index) in currentData" :key="index">
							<van-checkbox shape="square" class="fullCheck" v-if="item.F_DepartmentId" :name="item">{{
								item.F_FullName
							}}</van-checkbox>
							<span class="fullName" v-else @click="addDep(item, index)">{{ item.F_FullName }}</span>
							<!-- <van-icon v-if="item.children.length" name="arrow" class="icon-arrow" /> -->
							<span class="child-icon" v-if="item.children.length" @click.self.stop="addDep(item, index)">下级</span>
						</label>
					</van-checkbox-group>
				</template>
				<!-- 选人 -->
				<template v-if="type == 2">
					<!-- 单选人 -->
					<template v-if="!multiple">
						<template v-if="filterEmpData.length > 0">
							<label
								class="cell-item-dep bottom-line"
								@click="addEmp(item, index)"
								v-for="(item, index) in filterEmpData"
								:key="index"
							>
								<span class="fullName"
									><img class="head-imag" v-if="item.F_HeadIcon" :src="item.F_HeadIcon" /><span
										>{{ item.F_FullName || item.F_RealName
										}}{{ `${item.user_count ? `(${item.user_count})` : ""}` }}</span
									></span
								>
								<van-icon v-if="item.children && item.children.length" name="arrow" class="icon-arrow" />
							</label>
						</template>
						<template v-else-if="filterEmpData.length == 0 && searchStatus">
							<div class="empty_img" style="width:40%;padding-top:40%;"></div>
						</template>
						<template v-else>
							<label
								class="cell-item-dep bottom-line"
								@click="addEmp(item, index)"
								v-for="(item, index) in currentData"
								:key="index"
							>
								<span class="fullName"
									><img class="head-imag" v-if="item.F_HeadIcon" :src="item.F_HeadIcon" /><span
										>{{ item.F_FullName || item.F_RealName
										}}{{ `${item.user_count ? `(${item.user_count})` : ""}` }}</span
									></span
								>
								<van-icon v-if="item.children && item.children.length" name="arrow" class="icon-arrow" />
							</label>
						</template>
					</template>
					<!-- 多选人 -->
					<template v-if="multiple">
						<!-- 显示查询结果 -->
						<template v-if="filterEmpData.length > 0">
							<label class="cell-item-dep bottom-line" v-for="(item, index) in filterEmpData" :key="index">
								<van-checkbox
									shape="square"
									class="fullCheck"
									v-if="!item.children"
									:value="checkSlected(item).checked"
									@click="selecetUser(item)"
									><img class="head-imag" v-if="item.F_HeadIcon" :src="item.F_HeadIcon" /><span
										>{{ item.F_FullName || item.F_RealName
										}}{{ `${item.user_count ? `(${item.user_count})` : ""}` }}</span
									></van-checkbox
								>
								<span class="fullName" v-else @click="addEmp(item, index)"
									><img class="head-imag" v-if="item.F_HeadIcon" :src="item.F_HeadIcon" /><span
										>{{ item.F_FullName || item.F_RealName
										}}{{ `${item.user_count ? `(${item.user_count})` : ""}` }}</span
									></span
								>
								<van-icon v-if="item.children && item.children.length > 0" name="arrow" class="icon-arrow" />
							</label>
						</template>
						<template v-else-if="filterEmpData.length == 0 && searchStatus">
							<div class="empty_img" style="width:40%;padding-top:40%;"></div>
						</template>
						<!-- 非搜索结果 -->
						<template v-else>
							<label class="cell-item-dep bottom-line" v-for="(item, index) in currentData" :key="index">
								<van-checkbox
									shape="square"
									class="fullCheck"
									v-if="!item.children"
									:value="checkSlected(item).checked"
									@click="selecetUser(item)"
									><img class="head-imag" v-if="item.F_HeadIcon" :src="item.F_HeadIcon" /><span
										>{{ item.F_FullName || item.F_RealName
										}}{{ `${item.user_count ? `(${item.user_count})` : ""}` }}</span
									></van-checkbox
								>
								<span class="fullName" v-else @click="addEmp(item, index)"
									><img class="head-imag" v-if="item.F_HeadIcon" :src="item.F_HeadIcon" /><span
										>{{ item.F_FullName || item.F_RealName
										}}{{ `${item.user_count ? `(${item.user_count})` : ""}` }}</span
									></span
								>
								<van-icon v-if="item.children && item.children.length > 0" name="arrow" class="icon-arrow" />
							</label>
						</template>
					</template>
					<!-- 人员查询结果数据 -->
				</template>
				<template v-if="currentData.length == 0">
					<div class="empty_img" style="width:40%;padding-top:40%;"></div>
				</template>
			</div>
			<div class="select-group-data" v-if="multiple">
				<!-- <div class="count">已选{{selectData.length}}</div> -->
				<van-button :disabled="selectData.length == 0" block type="info" @click="changeData">确定</van-button>
			</div>
		</div>
	</transition>
</template>
<script>
let filterData = [];
let getChildUser = function(id, companyId, Keyword) {
	var params = {
		Company_Id: companyId,
		limit: 1,
		size: 1000,
		Keyword: Keyword,
		Department_Id: id,
	};
	return axiosHttp.get(`/users/page`, {
		params: params,
	});
};
let getDeps = function(id) {
	return axiosHttp.get(`/companies/${id}/departments/tree`);
};
export default {
	name: "selectDep",
	props: {
		show: false,
		type: {
			type: Number | String,
			default: 1,
		},
		multiple: {
			type: Boolean,
			default: false,
		},
		data: {
			type: Array,
			default: () => [],
		},
		select: {
			type: Array,
			default: () => [],
		},
		load: {
			type: Function,
			default: (item, resolve) => {
				resolve([]);
			},
		},
	},
	data() {
		return {
			showPanel: false,
			checked: true,
			keyword: "",
			stepList: [
				{
					name: "通讯录",
					currentData: this.data,
				},
			],
			searchStatus: false,
			// placeholder:"输入关键字搜索部门",
			currentData: this.data,
			selectData: [],
			filterEmpData: [], //查询数据
		};
	},
	computed: {
		placeholder() {
			return this.type == 1 ? "输入关键字搜索部门" : "输入关键字搜索人员";
		},
	},
	methods: {
		//内置查询用来覆盖原来的接口
		loadFn(item, resolve) {
			console.log("查询");
			getChildUser(item.F_DepartmentId, item.F_CompanyId, item.Keyword).then((res) => {
				resolve(res.data.Rows);
			});
		},
		findData(arr, data) {
			arr.forEach((item) => {
				if (item[data.key] && item[data.key].indexOf(data.value) > -1) {
					filterData.push(item);
				}
				if (item.children && item.children.length > 0) {
					this.findData(item.children, data);
				}
			});
		},
		onSearch(v) {
			//查询人员
			filterData = [];
			this.searchStatus = true;
			if (v.trim() == "") {
				this.filterEmpData = [];
				this.searchStatus = false;
				this.currentData = this.stepList[this.stepList.length - 1].currentData;
				console.log(this.filterEmpData, this.searchStatus);
				return;
			}
			if (this.type == "2") {
				//   console.log(this.currentData);
				//查询人员
				//全公司下查询人员
				//  if(this.currentData[0]&&this.currentData[0].F_ParentId=="0"&&!this.currentData[0].F_DepartmentId){

				//     new Promise((resolve, reject)=>{

				//         return this.loadFn?this.loadFn({F_CompanyId:this.currentData[0].F_CompanyId,Keyword:v},resolve):this.load({F_CompanyId:this.currentData[0].F_CompanyId,Keyword:v},resolve);
				//     }).then(data=>{
				//         this.filterEmpData=data;
				//     })
				// }else{
				//             //查询非全公司人员
				//             this.findData(this.currentData,{
				//                     key:"F_RealName",
				//                     value:v,
				//             });
				//             this.filterEmpData=filterData;
				// }
				// 迭代为搜索全部成员
				new Promise((resolve, reject) => {
					this.loadFn
						? this.loadFn({ F_CompanyId: this.currentData[0].F_CompanyId, Keyword: v }, resolve, reject)
						: this.load({ F_CompanyId: this.currentData[0].F_CompanyId, Keyword: v }, resolve, reject);
				}).then((data) => {
					this.filterEmpData = data;
				});
			}

			if (this.type == "1") {
				//查询符合条件部门
				if (v == "") {
					this.currentData = this.stepList[this.stepList.length - 1].currentData;
					return;
				}
				filterData = [];
				this.findData(this.data, {
					key: "F_FullName",
					value: v,
				});
				this.currentData = filterData.sort(function(a, b) {
					if (a.children.length > b.children.length) {
						return -1;
					} else if (a.length < b.length) {
						return 1;
					} else {
						return 0;
					}
				});
			}
		},
		selectDep(item, index) {
			if (!item.F_DepartmentId) {
				return;
			}
			console.log(item.Company_Id);
			console.log(item, "单选部门");
			this.$emit("update:show", false);
			this.$emit("selected", item);
			window.history.go(-1);
		},
		//检测是否被选中
		checkSlected(item) {
			var checked = false;
			var checkIdx = null;
			var selecteData = this.selectData;
			for (let index = 0; index < selecteData.length; index++) {
				//  console.log(checkIdx,'checkIdx');
				if (selecteData[index].F_UserId == item.F_UserId) {
					checkIdx = index;
					checked = true;
					break;
				}
			}
			return {
				checked: checked,
				idx: checkIdx,
			};
		},
		selecetUser(item, index) {
			let { checked, idx } = this.checkSlected(item);
			if (checked) {
				console.log("选中", idx);
				this.selectData.splice(idx, 1);
			} else {
				this.selectData.push(item);
				console.log("未选中");
			}
			console.log(this.selectData);
		},
		addDep(item, index) {
			//部门
			if (item.children.length == 0 && this.type == 1) {
				this.$emit("update:show", false);
				this.$emit("selected", item);
				window.history.go(-1);

				return;
			}
			this.stepList.push({
				name: item.F_FullName,
				id: item.F_DepartmentId || item.ID,
				currentData: item.children,
			});
			var currentData = item.children;
			this.currentData = currentData.sort(function(a, b) {
				if (a.children.length > b.children.length) {
					return -1;
				} else if (a.length < b.length) {
					return 1;
				} else {
					return 0;
				}
			});
			this.scrollActive();
		},
		async addEmp(item) {
			console.log("点击人员列表", !item.F_DepartmentId && item.ID);
			if (!item.F_DepartmentId && item.ID) {
				try {
					await getDeps(item.F_CompanyId).then((res) => {
						item.children = res.data;
					});
				} catch (error) {}
			}
			//点击人员
			if (item.children && item.children.length == 0 && this.type == 2) {
				new Promise((resolve, reject) => {
					console.log("加载子集人员");
					if (this.load && item.F_DepartmentId) {
						this.loadFn ? this.loadFn({ ...item, Keyword: this.keyword }, resolve) : this.load(item, resolve);
					} else {
						resolve([]);
					}
				}).then((data) => {
					this.stepList.push({
						name: item.F_FullName,
						id: item.F_DepartmentId || item.ID,
						currentData: data,
					});
					this.currentData = data;
					this.scrollActive();
					console.log("加载人员结束");
				});
				return;
			} else {
				if (item.F_UserId) {
					this.$emit("update:show", false);
					this.$emit("selected", item);
					window.history.go(-1);
					return;
				}
				new Promise((resolve, reject) => {
					console.log("加载非子集人员");
					if (this.load && item.F_DepartmentId) {
						this.loadFn ? this.loadFn({ ...item, Keyword: this.keyword }, resolve) : this.load(item, resolve);
					} else {
						resolve([]);
					}
				}).then((data) => {
					var currentData = item.children.concat(data);
					console.log(currentData);
					this.stepList.push({
						name: item.F_FullName,
						id: item.F_DepartmentId || item.ID,
						currentData: currentData,
					});
					if (currentData) {
						this.currentData = currentData.sort(function(a, b) {
							if (a.children && b.children) {
								if (a.children.length > b.children.length) {
									return -1;
								} else if (a.children.length < b.children.length) {
									return 1;
								} else {
									return 0;
								}
							} else {
								return 0;
							}
						});
					}
					this.scrollActive();
				});
				return;
			}
		},
		movereturn(e) {
			return false;
		},
		scrollActive() {
			this.$nextTick(() => {
				this.scrollNav = this.$refs.scrollNav;
				this.scrollNav.scrollLeft = this.scrollNav.scrollWidth;
			});
		},
		touchmove(e) {
			console.log(e);
		},
		active(index) {
			this.keyword = "";
			this.filterEmpData = [];
			this.stepList.splice(index + 1);
			this.currentData = this.stepList[index].currentData.sort(function(a, b) {
				if (a.children && b.children) {
					if (a.children.length > b.children.length) {
						return -1;
					} else if (a.children.length < b.children.length) {
						return 1;
					} else {
						return 0;
					}
				} else {
					return 0;
				}
			});
			this.scrollActive();
		},
		changeData() {
			// 返回选中的数据
			this.$emit("update:show", false);
			this.$emit("selected", this.selectData);
		},
		popStateEvent() {
			this.$emit("update:show", false);
			// history.go(-1);
			// history.pushState(null, null, location.href);
		},
	},
	mounted() {
		this.$nextTick(() => {
			document.body.appendChild(this.$el);
		});
	},
	watch: {
		select() {
			if (this.select.length) {
				this.selectData = this.select;
			}
		},
		keyword(v) {
			if (v.trim() == "") {
				this.searchStatus = false;
			}
		},
		show: {
			handler: function(v, old) {
				this.showPanel = v;
				if (v) {
					// window.addEventListener("hashchange", this.changehash);
					// window.location.hash = "deep";
					// Object.keys(this.$options.data()).forEach((key) => {
					// 	this[key] = this.$options.data()[key];
					// });
					document.body.style.overflow = "hidden";
					history.pushState(null, null, location.href);
					window.addEventListener("popstate", this.popStateEvent);
					this.$nextTick(() => {
						this.scrollActive();
					});
				} else {
					if (old !== undefined) {
						document.body.style.overflow = "";
						window.removeEventListener("popstate", this.popStateEvent);
					}
				}
			},
			immediate: true,
		},
		data(v) {
			if (v) {
				this.stepList = [
					{
						name: "通讯录",
						currentData: v,
					},
				];
				this.currentData = v;
			}
		},
	},
};
</script>

<style lang="less" scoped>
.right-enter-active,
.fade-leave-active {
	transition: all 0.3s;
	opacity: 1;
	transform: translateX(0);
	box-shadow: 0px 0px 10px grey;
}
.right-enter,
.fade-leave-to {
	transform: translateX(100%);
	opacity: 0;
}

.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
	will-change: transform;
	transition: all 500ms;
	position: absolute;
	width: 100%;
	height: 100%;
}
.slide-right-enter {
	opacity: 0;
	transform: translate3d(-100%, 0, 0);
}
.slide-right-leave-active {
	opacity: 0;
	transform: translate3d(100%, 0, 0);
}
.slide-left-enter {
	opacity: 0;
	transform: translate3d(100%, 0, 0);
}
.slide-left-leave-active {
	opacity: 0;
	transform: translate3d(100%, 0, 0);
}

.bottom-line::before {
	position: absolute;
	bottom: 0;
	width: 200%;
	height: 0px;
	left: 0;
	content: "";
	display: block;
	border-bottom: 1px solid #dedede;
	transform: scale(0.5);
	transform-origin: left bottom;
}
.select-box {
	font-size: 14px;
	position: fixed;
	overflow: hidden;
	height: 100%;
	width: 100%;
	top: 0px;
	left: 0px;
	bottom: 0px;
	right: 0px;
	z-index: 999;
	box-sizing: border-box;
	.select-group-data {
		position: fixed;
		bottom: 0px;
		left: 0px;
		width: 100%;
		background: #fff;
		height: 60px;
		display: flex;
		box-sizing: border-box;
		overflow: hidden;
		align-items: center;
		box-shadow: 0px 0px 10px #eee;
		padding: 10px;
		.count {
			font-size: 14px;
			width: 110px;
			text-align: center;
			font-weight: bold;
		}
	}
	.search {
		width: 90%;
	}
	.search /deep/ .van-search__content {
		width: 90%;
		border-radius: 100px;
	}
	&::before {
		content: "";
		display: block;
		clear: both;
	}
	.head-nav {
		user-select: none;
		width: 100%;
		height: 40px;
		flex-wrap: nowrap;
		overflow: hidden;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 0px 10px;
		box-sizing: border-box;
		position: absolute;
		top: 50px;
		z-index: 10;
		box-shadow: 0px 4px 10px #eee;
		.nav-scroll {
			width: 100%;
			height: 55px;
			overflow: hidden;
			overflow-x: scroll;
			white-space: nowrap;
			box-sizing: border-box;
			.nav-item {
				min-width: 0px;
				white-space: nowrap;
				display: inline-block;
				height: 100%;
				max-width: 80%;
				text-overflow: ellipsis;
				line-height: 55px;
				align-items: center;
				font-weight: bold;
				overflow: hidden;
				position: relative;
				padding: 0px 5px;
				&.active {
					color: rgb(31, 118, 250);
				}
			}
		}
	}
	.container {
		padding-top: 100px;
		position: absolute;
		top: 0;
		height: 100%;
		box-sizing: border-box;
		width: 100%;
		background-color: #fafafa;
		overflow: auto;

		.cell-item-dep,
		.cell-item-emp {
			display: flex;
			letter-spacing: 1px;
			width: 100%;
			min-height: 50px;
			align-items: center;
			padding: 5px 15px;
			box-sizing: border-box;
			//color:#585858;
			background: #fff;
			position: relative;
			/deep/ .van-checkbox {
				width: 100%;
			}
			&:active {
				background: #fafafa;
			}
			.fullName {
				height: 100%;
				display: flex;
				align-items: center;
				// padding-top:10px;padding-bottom:10px;
			}
			/deep/ .van-checkbox__label {
				display: flex;
				align-items: center;
				padding-top: 5px;
				padding-bottom: 5px;
			}
			.head-imag {
				width: 40px;
				height: 40px;
				border-radius: 50%;
				margin-right: 5px;
				object-fit: cover;
			}
			.child-icon {
				display: flex;
				width: 80px;
				text-align: center;
				padding: 0px 10px;
				box-sizing: border-box;
				color: rgb(31, 118, 250);
				border-left: solid 1px #eee;
			}
		}
		.cell-item-dep {
			font-weight: bold;
			box-sizing: border-box;

			.fullName {
				width: 100%;
			}
		}
	}

	&.multiple {
		.container {
			padding-bottom: 60px;
		}
	}
	.select-search {
		position: absolute;
		height: 50px;
		width: 100%;
		z-index: 1;
		background: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		input {
			background: #eee;
		}
	}
}
.empty_img {
	&::before {
		display: block;
		content: "暂无内容~";
		text-align: center;
		position: absolute;
		bottom: -20px;
		font-size: 14px;
		left: 50%;
		white-space: nowrap;
		color: #c1c1c1;
		transform: translateX(-50%);
	}
	position: relative;
	margin: auto;
	margin-top: 30%;
	background-size: 100%;
	background-repeat: no-repeat;
	background-image: url();
}
</style>
